package com.train.course.service.impl;

import com.train.course.domain.VideoLike;
import com.train.course.mapper.VideoLikeMapper;
import com.train.course.mapper.VideoEpisodeMapper;
import com.train.course.service.IVideoLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 视频点赞 服务层实现
 */
@Service
public class VideoLikeServiceImpl implements IVideoLikeService {

    @Autowired
    private VideoLikeMapper videoLikeMapper;

    @Autowired
    private VideoEpisodeMapper videoEpisodeMapper;

    /**
     * 点赞视频 - 切换模式（已点赞则取消点赞）
     */
    @Override
    @Transactional
    public boolean likeVideo(Long userId, Long videoId) {
        // 检查是否已经点赞
        VideoLike existingLike = videoLikeMapper.selectVideoLikeByUserAndVideo(userId, videoId, "1");
        if (existingLike != null) {
            // 已经点赞过了，执行取消点赞
            return unlikeVideo(userId, videoId);
        }

        // 插入点赞记录
        VideoLike videoLike = new VideoLike();
        videoLike.setUserId(userId);
        videoLike.setVideoId(videoId);
        videoLike.setVideoType("1"); // 视频集类型
        videoLike.setCreateBy(String.valueOf(userId));
        
        int likeResult = videoLikeMapper.insertVideoLike(videoLike);
        if (likeResult <= 0) {
            return false;
        }

        // 增加视频点赞数
        int countResult = videoEpisodeMapper.incrementLikeCount(videoId);
        return countResult > 0;
    }

    /**
     * 取消点赞
     */
    @Override
    @Transactional
    public boolean unlikeVideo(Long userId, Long videoId) {
        // 检查是否已经点赞
        VideoLike existingLike = videoLikeMapper.selectVideoLikeByUserAndVideo(userId, videoId, "1");
        if (existingLike == null) {
            return false; // 没有点赞记录
        }

        // 删除点赞记录
        int likeResult = videoLikeMapper.deleteVideoLikeByUserAndVideo(userId, videoId, "1");
        if (likeResult <= 0) {
            return false;
        }

        // 减少视频点赞数
        int countResult = videoEpisodeMapper.decrementLikeCount(videoId);
        return countResult > 0;
    }

    /**
     * 检查用户是否已点赞
     */
    @Override
    public boolean isLiked(Long userId, Long videoId) {
        VideoLike existingLike = videoLikeMapper.selectVideoLikeByUserAndVideo(userId, videoId, "1");
        return existingLike != null;
    }
}